import React, {Component} from 'react'
import StyleUtils from "../../res/styles/StyleUtils";
import Navigation from "../../custom/Navigation";
import {
    Animated,
    DeviceEventEmitter,
    Image,
    ListView,
    ScrollView,
    StyleSheet,
    Text,
    TouchableOpacity,
    View
} from "react-native";
import GoodsRender from "../../utils/GoodsRender";
import IparNetwork, {IMAGE_URL, SERVER_TYPE} from "../../httpUtils/IparNetwork";
import GoodsPage from "../common/GoodsPage";
import I18n from "../../res/language/i18n";
import ViewUtils from "../../utils/ViewUtils";
import CommonUtils from "../../common/CommonUtils";
import IparImageView from "../../custom/IparImageView";

let ds = new ListView.DataSource({
    rowHasChanged: (r1, r2) => r1 !== r2
});
export default class CategoryMinPage extends Component {


    constructor(props) {
        super(props);


        this.categoryData = [];
        this.state = {
            dataSource: ds,
            dataSourceMenu: ds,
            dataSourceItem: ds,
            adverData: null,
            menuHeight: new Animated.Value(0),
            isOpenMenu: false,
            menuLength: 0,
            menuTitle: I18n.t('default.selectionClassification'),
        }
    }


    componentDidMount() {
        this.loadData();
    }


    /**
     * 获取信息
     * @param country
     */
    loadData(country) {

        CommonUtils.showLoading();

        new IparNetwork().getRequest(SERVER_TYPE.goods + 'goodsCate?',
            'country=' + this.props.country + '&cate_id=' + this.props.cate_id)//cate_id=0为父分类
            .then((result) => {
                if (result.code === 200) {
                    let dataBlob = result.data.category;
                    this.categoryData = dataBlob;

                    this.setState({
                        adverData: result.data.top,
                        dataSource: ds.cloneWithRows(dataBlob),
                        dataSourceMenu: ds.cloneWithRows(dataBlob),
                        menuLength: dataBlob.length,
                    })
                } else {

                    DeviceEventEmitter.emit('toast', '失败')
                }
                CommonUtils.dismissLoading();

            })
            .catch((error) => {

                CommonUtils.dismissLoading();

                console.log('CategoryTableTowView---loadData--error: ', error);
                DeviceEventEmitter.emit('toast', '失败')
            })

    }


    getListView(dataSource, renderRow, style) {
        return <ListView
            renderRow={renderRow}
            contentContainerStyle={style}
            dataSource={dataSource}/>
    }


    /**
     * 菜单点击
     */
    onItemClickMenu(index) {
        this.closeMenu();
        this.setState({
            menuTitle: this.getMenuText(this.categoryData[index]),
            dataSource: ds.cloneWithRows([this.categoryData[index]])
        });
    }

    renderMenuItem(rowData, rowID) {
        let _name = this.getMenuText(rowData);

        return (<TouchableOpacity
                onPress={() => this.onItemClickMenu(rowID)}
                style={[StyleUtils.justifySpace, {marginLeft: 8, marginRight: 8, height: 38}]}
            >
                <Text style={[StyleUtils.text, {color: '#333'}]}>{_name}</Text>
                <Image
                    style={[StyleUtils.tabIconSize, {tintColor: '#999999'}]}
                    source={require('../../res/images/ic_right_more.png')}/>
            </TouchableOpacity>
        )
    }

    /**
     * 关闭菜单
     * */
    oponMenu() {
        this.setState({isOpenMenu: true});
        Animated.timing(       // 随时间变化而执行的动画类型
            this.state.menuHeight,   // 动画中的变量值
            {
                toValue: 38 * this.state.menuLength,   // 透明度最终变为1，即完全不透明
                duration: 500, // 动画时间
            }
        ).start();
    }

    /**
     * 打开菜单
     * */
    closeMenu() {
        this.setState({isOpenMenu: false});
        Animated.timing(       // 随时间变化而执行的动画类型
            this.state.menuHeight,   // 动画中的变量值
            {
                toValue: 0,   // 透明度最终变为1，即完全不透明
                duration: 500, // 动画时间
            }
        ).start();
    }


    renderMenuView() {
        return (<Animated.View
                style={{
                    height: this.state.menuHeight,
                    backgroundColor: '#f5f5f5',
                    marginRight: 16,
                    marginLeft: 16,
                    borderBottomRightRadius: 4,
                    borderBottomLeftRadius: 4,
                }}>

                <ListView
                    dataSource={this.state.dataSourceMenu}
                    renderRow={(rowData, sectionID, rowID) => this.renderMenuItem(rowData, rowID)}
                />

            </Animated.View>
        )
    }

    render() {
        return (
            <View style={[StyleUtils.flex]}>
                <Navigation
                    onClickLeftBtn={() => this.props.navigator.pop()}
                    title={this.props.title}
                />

                <ScrollView>
                    {/**广告*/}
                    {this.state.adverData &&
                    <IparImageView
                        resizeMode={'cover'}
                        errorImage={require('../../res/images/ic_image_fail.png')}
                        width={'100%'}
                        height={200} url={this.state.adverData.adver_img}/>}


                    <View style={[{marginRight: 16, marginLeft: 16, marginTop: 16}]}>
                        {ViewUtils.getButton(this.state.menuTitle, () => {
                            this.state.isOpenMenu ? this.closeMenu() : this.oponMenu();
                        }, {
                            height: 46,
                            backgroundColor: 'white',
                            borderWidth: 1,
                            borderColor: '#cfcfcf'
                        }, {
                            color: 'black',
                            fontSize: 14
                        })}
                    </View>

                    {this.renderMenuView()}

                    {this.getListView(this.state.dataSource, this._renderListView.bind(this))}


                </ScrollView>


            </View>
        )
    }


    getMenuText(rowData) {
        if (!rowData) return ' ';
        let _name = rowData.name;
        switch (I18n.locale) {
            case 'uy':
                _name = rowData.name_uy ? rowData.name_uy : _name;
                break;
            case 'en':
                _name = rowData.name_en ? rowData.name_en : _name;
                break;
            case 'ru':
                _name = rowData.name_ru ? rowData.name_ru : _name;
                break;
        }
        return _name;
    }

    _renderListView(rowData) {


        let _name = this.getMenuText(rowData);


        return (
            <View>
                <Text style={[StyleUtils.title, StyleUtils.smallFont, {textAlign: null, padding: 16}]}>
                    {_name}
                </Text>
                {this.getListView(
                    this.state.dataSourceItem.cloneWithRows(rowData.goods),
                    this._renderRowGoods.bind(this),
                    styles.gridListStyle)}
            </View>
        )
    }


    onItemClick(rowData) {
        this.props.navigator.push({
            component: GoodsPage,
            name: 'GoodsPage',
            params: {
                goodsInfo: rowData
            }
        });
    }

    _renderRowGoods(rowData) {
        return (
            <GoodsRender
                onPress={() => this.onItemClick(rowData)}
                navigator={this.props.navigator}
                dataSource={rowData}/>
        )
    }
}

const styles = StyleSheet.create({
    gridListStyle: {
        flexDirection: 'row',
        flexWrap: 'wrap'
    },
});